package framework;

import interfaces.Board;
import interfaces.State;
import interfaces.Visualizer;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.HashMap;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** 
 * An abstract class that can be extended by a plugin developer
 * to customize the way the automata are painted. It also
 * has a generic paint method.
 */
@SuppressWarnings("serial")
public abstract class VisualizerAbstract extends JPanel implements Visualizer {
	private final int IMAGE_SIZE = 10;

	HashMap<Class<?>, Object> stateVisualObjects = new HashMap<Class<?>, Object>();
	
	/** 
	 * The constructor for the visualizer - sets up the box that
	 * will display the cellular automata
	 * @param board - the board used by the visualizer
	 */
	public VisualizerAbstract(Board board)
	{
		int panelWidth = board.getWidth() * IMAGE_SIZE;
		int panelHeight = board.getHeight() * IMAGE_SIZE;
		Dimension preferredSize = new Dimension(panelWidth, panelHeight);
		this.setPreferredSize(preferredSize);
		this.setBackground(Color.WHITE);
		//this.setVisible(true);
		
		//here we need to instantiate JFrame so that 
		//we get to see visual interface
		JFrame f = new JFrame("Cellular Automaton");
		f.add(this);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.pack();
		f.setResizable(false);
		f.setVisible(true);		
	}
	
	@Override	
	public void setStateIcon(State state, ImageIcon icon) {
		stateVisualObjects.put(state.getClass(), icon);
	}

	@Override
	public void setStateColor(State state, Color color) {
		stateVisualObjects.put(state.getClass(), color);
	}

	
	public void paint(State state, int i, int j){
		Object visObj = stateVisualObjects.get(state.getClass());
		if(visObj instanceof ImageIcon)
			paint((ImageIcon)visObj, i, j);
		else if(visObj instanceof Color)
			paint((Color)visObj, i, j);		
	}
	
	/**
	 * Implementation of painting a single color square at location i,j
	 * of size IMAGE_SIZE
	 * @param icon the icon to paint
	 * @param i row of cell
	 * @param j col of cell
	 */
	private void paint(Color color, int i, int j){
		//get graphic object from JPanel
		//we inherit from it
		Graphics g = this.getGraphics();
		g.setColor(color);
		g.fillRect(j*IMAGE_SIZE, i*IMAGE_SIZE, IMAGE_SIZE, IMAGE_SIZE);
	}

	/**
	 * This paints the icon
	 * @param icon the icon to paint
	 * @param i row of cell
	 * @param j col of cell
	 */
	private void paint(ImageIcon icon, int i, int j){
		Graphics g = this.getGraphics();
		icon.paintIcon(this, g, j*IMAGE_SIZE, i*IMAGE_SIZE);
	}
}	